package com.ms.hotevent.controller;

import com.ms.hotevent.entity.Comment;
import com.ms.hotevent.entity.Event;
import com.ms.hotevent.entity.User;
import com.ms.hotevent.service.CommentService;
import com.ms.hotevent.service.EventService;
import com.ms.hotevent.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@Slf4j
public class EventController {

    @Autowired
    EventService eventService;

    @Autowired
    CommentService commentService;

    @Autowired
    UserService userService;

    private static final String INDEX_PAGE = "index";
    private static final String DETAIL_PAGE = "detail";

    @RequestMapping("/")
    public String index(Model model,
                        @RequestParam(value = "page",defaultValue = "1") Integer pageIndex,
                        @RequestParam(value = "pageRows",defaultValue = "5") Integer pageRows,
                        Event event,
                        String sort,
                        String order){
        if(pageIndex == null || pageIndex <= 0){
            pageIndex = 1;
        }
        int pageCount = eventService.queryPagesCount(pageRows,event);
        if(pageIndex > pageCount){
            pageIndex = pageCount;
        }
        log.info("Entering index p:{} r:{} title:{}",pageIndex,pageRows,event.getTitle());
        List<Event> events = eventService.query(pageIndex,pageRows,event,sort,order);
        model.addAttribute("events",events);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("pageCount",pageCount);
        model.addAttribute("event",event);
        model.addAttribute("sort",sort);
        model.addAttribute("order",order);
        log.info("Exiting index");
        return INDEX_PAGE;
    }

    @RequestMapping("/detail")
    public String detail(Model model,Integer id){
        if (id == null) {
            log.warn("Invalid event id: null");
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid event id: null");
        }
        log.info("Entering detail with id:{}", id);
        eventService.updateSearchIndex(id,1);
        model.addAttribute("event",eventService.getOne(id));
        model.addAttribute("comments",commentService.getComments(id));
        log.info("Exiting detail");
        return DETAIL_PAGE;
    }

    @RequestMapping("/addcommnet")
    public String addComment(Comment comment,HttpSession session){
        User user = (User) session.getAttribute("user");
        comment.setUser(user);
        log.info("Entering addComment");
        eventService.updateSearchIndex(comment.getEventId(),10);
        if (commentService.add(comment)) {
            log.info("Exiting addComment");
            return "redirect:detail?id="+comment.getEventId();
        } else {
            log.error("Error in adding comment");
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Error in adding comment");
        }
    }

    @RequestMapping("/addevent")
    public String addEvent(Event event,HttpSession session){
        User user = (User) session.getAttribute("user");
        event.setUser(user);
        eventService.add(event);
        return "redirect:/";
    }

    @RequestMapping("/login-pre")
    public String loginPre(HttpServletRequest request){
        log.info("前一个页面的地址:{}",request.getHeader("Referer"));
        request.setAttribute("referer",request.getHeader("Referer"));
        return "login";
    }

    @RequestMapping("/login")
    public String login(String email, String password,String verifyCode, HttpSession session,String url){
        Boolean loginFailed = (Boolean) session.getAttribute("loginFailed");
        if (loginFailed!=null && loginFailed){
            String verifyCodeServer = (String) session.getAttribute("verifyCode");
            if(!verifyCodeServer.equals(verifyCode)){
                throw new RuntimeException("验证码不对");
            }
        }
        User user = userService.login(email, password);
        if(user != null) {
            session.setAttribute("user",user);
            log.info("登录成功:{}",user);
            session.removeAttribute("loginFailed");
            return "redirect:"+url;
        }else{
            log.info("登录失败");
            // 登录失败，记录这个信息
            session.setAttribute("loginFailed", true);
            return "redirect:/login-pre";
        }
    }

    @RequestMapping("/register-pre")
    public String registerPre(){
        return "register";
    }

    @RequestMapping("/register")
    public String register(User user,String verifyCode,HttpSession session){
        String verifyCodeServer = (String) session.getAttribute("verifyCode");
        if(!verifyCodeServer.equals(verifyCode)){
            throw new RuntimeException("验证码不对");
        }
        userService.add(user);
        return "redirect:/login-pre";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
}
